package com.lambkit.auth.sms;

import cn.hutool.core.util.StrUtil;
import com.lambkit.LambkitConsts;
import com.lambkit.core.Lambkit;

public abstract class AbstractSmsLoginService implements SmsLoginService {
	
	public abstract int sendLoginVerifyCode(String phoneTo, String code);

	@Override
	public int sendCode(String phoneTo) {
		String cacheVerifyCode = Lambkit.getCache().get(LambkitConsts.SMS_CACHE_PHONE, phoneTo);
		if(StrUtil.isNotBlank(cacheVerifyCode)) {
			return 10501;
		}
		// 生成六位验证码
		String code = vcode();
		// 将生成的六位验证码和传进来的手机号码存入缓存，时间5分钟
		Lambkit.getCache().put(LambkitConsts.SMS_CACHE_PHONE, phoneTo, code, 300);
		return sendLoginVerifyCode(phoneTo, code);
	}

	@Override
	/**
	 * 验证短信验证码登陆
	 * @param to 手机号
	 * @param verifyCode
	 * @return
	 */
	public boolean verifyCode(String to, String verifyCode) {
		if(StrUtil.isBlank(verifyCode)) {
			return false;
		}
		// 缓存中验证码
		String cacheVerifyCode = Lambkit.getCache().get(LambkitConsts.SMS_CACHE_PHONE, to);
		//Printer.print(this, "auth"("mobile: " + to + ", code: " + cacheVerifyCode + ", verifyCode: " + verifyCode);
		// 如果赎金来的验证码和缓存中的验证码一致，则验证成功
		if (verifyCode.equals(cacheVerifyCode)) {
			return true;
		}
		return false;
	}

	/**
	 * 生成6位随机数验证码
	 * 
	 * @return
	 */
	public String vcode() {
		String vcode = "";
		for (int i = 0; i < 6; i++) {
			vcode = vcode + (int) (Math.random() * 9);
		}
		return vcode;
	}

}
